package com.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;

/**
 * 公共工具类
 * @author PF0P65Z6
 *
 */
public class CommonUtil {
	
	/**
	 * blob转string
	 * @param blob
	 * @return
	 */
	public static String blobToString(Blob blob){
		String content = "";
		try{  
			content = new String(blob.getBytes((long)1, (int)blob.length()));  
	    } catch(SQLException e) {  
	         e.printStackTrace();  
	    }
		
		return content;
	}
	
	/**
	 * blob转string
	 * @param blob
	 * @return
	 */
	public static String blobToString2(Blob blob) {  
		InputStream in = null;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] data = new byte[4096];  
        int count = -1;  
        String result = null;
        try {
			in = blob.getBinaryStream();
			while ((count = in.read(data, 0, 4096)) != -1) {
				outStream.write(data, 0, count);
			}
			data = null;
			
			result = new String(outStream.toByteArray(), "gb2312");
		} catch (IOException e) {
			e.printStackTrace();
		}catch (SQLException e) {
			e.printStackTrace();
		} finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
        
        return result;  
  
    }  
	
	public static String clobToString(Clob clob){
		String content = null;
		Reader read = null;
        try {
			read = clob.getCharacterStream();
	        char[] c = new char[(int) clob.length()];
			read.read(c);
	        content = new String(c);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				read.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
        
        return content;
	}
	
	/**
	 * "?" 转为多个
	 * @param value
	 * @param size
	 * @return
	 */
	public static String formatString(String value, int size){
		StringBuilder sb = new StringBuilder("");
		for(int i = 0 ; i < size ; i++){
			sb.append(value).append(",");
		}
		
		if(sb.length() > 0){
			sb.deleteCharAt(sb.length()-1);
		}
		
		return sb.toString();
	}
}
